# coding:utf-8
class TerminalGroup < ActiveRecord::Base
  has_paper_trail :version => :paper_trail_version, :versions => :paper_trail_versions
  attr_accessible :description, :group_name, :city_id,:industry

  validates_presence_of :group_name
  validates_uniqueness_of :group_name,:scope => :city_id
  validates_presence_of :city_id

  has_many :terminals, dependent: :nullify
  has_many :traffic_strategies, dependent: :destroy
  has_many :terminal_orders, dependent: :nullify
  has_one :advertise_rule, :as => :advertise_ruleable, dependent: :destroy
  belongs_to :city

  after_create :create_advertise_rule

  def current_advertise_rule
    self.advertise_rule || self.city.advertise_rule || self.province.advertise_rule
  end

  def current_advertise_group
    current_advertise_rule.advertise_group if current_advertise_rule
  end

  def to_s
    group_name
  end

  def display_name
    [self.industry,self.group_name].join("-")
  end

  def permission_ancestors
    [self.city.province,self.city,self]
  end

  def zone
    [self.city.try(:province).try(:name),self.city.try(:name)].join("-")
  end

  def display_terminals_count
    "#{self.terminals_count} 台"
  end

  def display_traffic_strategies_count
    if self.traffic_strategies.count > 0
      "#{self.traffic_strategies.count} 条"
    else
      "未配置"
    end
  end

  def total_account_signin
    AccountSignin.count(:include => :terminal,:conditions => ["terminals.terminal_group_id = ?",self.id])
  end

  def total_register
    AccountSignin.count(:account_id,:distinct => true,:include => :terminal,:conditions => ["terminals.terminal_group_id = ?",self.id])
  end

  def this_advertise_group? advertise_group
    self.advertise_rule && self.advertise_rule.advertise_group_id && self.advertise_rule.advertise_group_id == advertise_group.id
  end

  def conflict_advertise_group? advertise_group
    self.advertise_rule && self.advertise_rule.advertise_group_id && self.advertise_rule.advertise_group_id != advertise_group.id
  end

  private

  def create_advertise_rule
    AdvertiseRule.create(advertise_ruleable_type: self.class.name,advertise_ruleable_id: self.id)
  end

end